package com.cherry.sdk.http.token

import com.cherry.sdk.http.params.Params
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.Buffer
import retrofit2.Converter
import java.io.OutputStreamWriter
import java.nio.charset.Charset

/**
 * @author 董棉生(dongmiansheng@parkingwang.com)
 * @since 18-11-16
 */

class TokenRequestConverter(private val tokenConfig: TokenConfig,
                            private val gson: Gson) : Converter<Params, RequestBody> {

    private val adapter = gson.getAdapter(TypeToken.get(Params::class.java))

    private val MEDIA_TYPE by lazy {
        MediaType.parse("application/json; charset=${tokenConfig.charsetEnCode}")
    }

    private val CHARSET_ENCODE by lazy {
        Charset.forName(tokenConfig.charsetEnCode)
    }

    override fun convert(value: Params): RequestBody {
        value[tokenConfig.tokenKey] = tokenConfig.tokenProvider.getToken()
        val buffer = Buffer()
        val writer = OutputStreamWriter(buffer.outputStream(), CHARSET_ENCODE)
        val jsonWriter = gson.newJsonWriter(writer)
        adapter.write(jsonWriter, value)
        jsonWriter.close()
        return RequestBody.create(MEDIA_TYPE, buffer.readByteString())
    }


}

